<template>
	<headerNavbarVue :isIcon="true"></headerNavbarVue>
	<uni-section type="line">
		<uni-notice-bar show-close show-icon single text="  绑定环线和商品不可修改,请仔细核对!" />
	</uni-section>
	<view class="publish-Page" :class="{'no-scroll': isPopupOpen}">
		<textarea auto-height maxlength="-1" v-model="ContentForm.trip_blog_title" class="input-title"
			placeholder-class="input-title-placeholder" placeholder="标题" />
		<textarea auto-height maxlength="-1" v-model="ContentForm.trip_blog_content" class="input-content"
			placeholder-class="input-content-placeholder" placeholder="写出你的旅程..." />
		<view class="imageUploader">
			<view class="image-list">
				<view v-for="(image, index) in imageList" :key="index" class="imageItem">
					<image :src="image" mode="aspectFill" class="image" @click="previewImage(index)"></image>
					<view class="delImg" @click="removeImage(index)">
						<image src="https://file.whshiyuan.cn:9000/toopu/compressed/1341729001464_compressed_img.png"
							mode=""></image>
					</view>
				</view>
				<view class="imageItem" v-if="imageList.length<9">
					<image class="addBtn" @click="chooseImage"
						src="https://file.whshiyuan.cn:9000/toopu/compressed/8311729060598_compressed_img.png" mode="">
					</image>
				</view>
			</view>
		</view>
		<SelectLoopPopupVue ref="childPopup" :isEditing="isEditing" :contentForm="ContentForm"
			@openPopup="handleOpenPopup" @closePopup="handleClosePopup" />
		<view class="publish-box" v-if="isEditing">
			<text @click="SubmitEdit">确认修改</text>
		</view>
		<view class="publish-box" v-else>
			<text @click="openPopupInParent">下一步</text>
		</view>
	</view>
</template>
<script setup>
	import headerNavbarVue from '@/components/headerNavbar.vue';
	import SelectLoopPopupVue from './components/SelectLoopPopup.vue';
	import {uploadFile,imageUrl} from '@/config/request/request.js'
	import { Postdetail, PutFixMyCommit } from '@/config/API/commit';
	import {ref} from 'vue';
	import { onLoad } from '@dcloudio/uni-app';

	const imageList = ref([]); // 本地图片列表
	const upAfterimageList = ref([]); // 上传后的图片列表
	const childPopup = ref(null);
	const isPopupOpen = ref(false);
	const isEditing = ref(false); // 判断是否为编辑模式
	const CommitDetail = ref()
	const ContentForm = ref({
		trip_blog_title: '',
		trip_blog_content: '',
		img_list: upAfterimageList.value,
	})

	// 获取社区ID，如果有则为编辑模式
	onLoad((options) => {
		const communityID = options.communityID;
		console.log('编辑获取到的 communityID:', communityID);
		if (communityID) {
			isEditing.value = true;
			loadCommunityData(communityID); // 加载编辑数据
		} else {
			isEditing.value = false;
		}
	});
	// 根据 communityID 加载数据 (这里需要你根据后台接口或本地存储来获取编辑数据)
	const loadCommunityData = async (communityID) => {
		try {
			const resData = await Postdetail(communityID);
			// 假设你有 API 来获取编辑数据，这里使用伪数据
			CommitDetail.value = resData.data
			ContentForm.value.trip_blog_title = CommitDetail.value.trip_blog_title;
			ContentForm.value.trip_blog_content = CommitDetail.value.trip_blog_content;
			upAfterimageList.value = CommitDetail.value.img_list;
			imageList.value = Object.values(CommitDetail.value.img_list).map(img => imageUrl + img);
			console.log('CommitDetail.value', CommitDetail.value);
			console.log('ContentForm.value', ContentForm.value);
			console.log('img_list:', CommitDetail.value.img_list);
			console.log('imageList.value:', imageList.value);
		} catch (e) {
			console.log('获取数据失败 :', e);
		}
	};
	
	// 表单验证提醒
	const validateField = (value, message) => {
		if (!value) {
			uni.showToast({
				title: message,
				icon: "none",
				duration: 2000
			});
			return false;
		}
		return true;
	};

	// 提交修改
	const SubmitEdit = async () => {
		// 验证必填项
		const isValidTitle = validateField(ContentForm.value.trip_blog_title, '标题不能为空');
		const isValidContent = validateField(ContentForm.value.trip_blog_content, '内容不能为空');
		const isValidImage = validateField(upAfterimageList.value.length > 0, '请上传图片');

		if (isValidTitle && isValidContent && isValidImage) {
			// 构造提交数据
			const formattedImgList = upAfterimageList.value
				.map(imageUrl => {
					// 提取文件名
					const fileName = imageUrl.split('/').pop();
					return `"/applet/static/${fileName}"`; // 文件名加双引号
				}).join(','); // 用逗号拼接成字符串

			const submitData = {
				community_share_id: CommitDetail.value.CommunityID, // ID
				trip_blog_title: ContentForm.value.trip_blog_title, // 标题
				trip_blog_content: ContentForm.value.trip_blog_content, // 内容
				img_list: `[${formattedImgList}]` // 图片列表，格式化为字符串
			};
			console.log('submitData',submitData);
			try {
				const response = await PutFixMyCommit(submitData);
				if (response.code == 200) {
					// 提交成功后的处理
					uni.showToast({
						title: '修改成功，等待审核',
						icon: 'none',
						duration: 1500
					});
					// 延迟后再跳转
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: '提交失败',
						icon: 'error',
						duration: 2000
					});
				}
			} catch (error) {
				console.log('提交失败：', error);
				uni.showToast({
					title: '提交失败，请稍后再试',
					icon: 'none',
					duration: 2000
				});
			}
		}
	};

	// 打开子组件的弹窗前的验证
	const openPopupInParent = () => {
		// 确保 img_list 是最新的 imageList 数据并格式化为字符串
		const formattedImgList = upAfterimageList.value
			.map(imageUrl => {
				// 提取图片文件名，假设 URL 是文件路径
				const fileName = imageUrl.split('/').pop();
				return `"/applet/static/${fileName}"`; // 文件名用双引号包裹
			})
			.join(','); // 通过逗号拼接

		// 将拼接后的 img_list 字符串赋给 ContentForm.value.img_list
		ContentForm.value.img_list = `[${formattedImgList}]`;

		// 验证必填项
		const isValidImage = validateField(imageList.value.length > 0, '请上传图片');
		const isValidContent = validateField(ContentForm.value.trip_blog_content, '内容不能为空');
		const isValidTitle = validateField(ContentForm.value.trip_blog_title, '标题不能为空');
		if (isValidTitle && isValidContent && isValidImage) {
			if (childPopup.value) {
				childPopup.value.openPopup();
			}
		}
		console.log('下一步 ContentForm', ContentForm.value);
	};
	// 监听子组件的事件来处理其他逻辑
	const handleOpenPopup = () => {
		console.log('弹窗打开');
		isPopupOpen.value = true;
	};

	const handleClosePopup = () => {
		console.log('弹窗关闭');
		isPopupOpen.value = false;
	};

	// 选择图片
	const chooseImage = () => {
		// 检查当前已选择的图片数量
		if (imageList.value.length >= 9) {
			uni.showToast({
				title: '最多只能上传 9 张图片',
				icon: 'none',
				duration: 2000
			});
			return; // 如果已经选择了 9 张图片，直接返回，不再执行后续代码
		}
		uni.chooseImage({
			count: 9 - imageList.value.length, // 允许选择的数量是 9 减去已经选择的图片数量
			success: async (res) => {
				const tempFiles = res.tempFilePaths;
				imageList.value = imageList.value.concat(tempFiles); // 将选择的图片路径添加到 imageList 中

				// 上传每张图片
				for (let index = 0; index < tempFiles.length; index++) {
					const item = tempFiles[index];
					try {
						const imageData = await uploadFile.upload(item); // 上传图片
						const isItemData = imageData.data[0]; // 获取上传成功的图片路径
						upAfterimageList.value.push(isItemData); // 将上传后的图片路径添加到 upAfterimageList 中
						console.log('上传图片', imageData.data);
					} catch (error) {
						console.error('上传失败', error);
					}
				}

				console.log('imageList', imageList.value);
				console.log('upAfterimageList.value', upAfterimageList.value);
			},
			fail: (err) => {
				console.log('选择图片失败', err);
			}
		});
	};

	// 删除图片
	const removeImage = (index) => {
		upAfterimageList.value.splice(index, 1);
		imageList.value.splice(index, 1);
		console.log('删除图片upAfterimageList.value', upAfterimageList.value);
	};

	// 预览图片
	const previewImage = (index) => {
		uni.previewImage({
			current: index,
			urls: imageList.value
		});
	};
</script>
<style lang="scss" scoped>
	.no-scroll {
		overflow: hidden;
		position: fixed;
		width: 100%;
		height: 100%;
	}

	.publish-Page {
		width: 100%;
		min-height: 75vh;
		padding: 30rpx;
		padding-top: 40rpx;
		padding-bottom: 240rpx;
		box-sizing: border-box;

		// background-color: #000;
		.input-title {
			width: 100%;
			height: 100%;
			font-size: 30rpx;
			padding: 20rpx 10rpx;
			box-sizing: border-box;
			border-bottom: 2rpx solid #ececec;
		}

		.input-content {
			width: 100%;
			min-height: 350rpx;
			font-size: 26rpx;
			color: #000020;
			font-weight: 300;
			padding: 40rpx 10rpx;
			box-sizing: border-box;
			margin-bottom: 50rpx;
		}

		.imageUploader {
			display: flex;
			flex-wrap: wrap;

			.image-list {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				.imageItem {
					width: 200rpx;
					height: 200rpx;
					background: #F2F2F2;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					position: relative;
					overflow: hidden;

					.image {
						width: 100%;
						height: 100%;
						border-radius: 10rpx;
					}

					.delImg {
						position: absolute;
						top: 8rpx;
						right: 14rpx;

						image {
							width: 28rpx;
							height: 28rpx;
						}
					}

					.addBtn {
						width: 100%;
						height: 100%;
						background-color: #f0f0f0;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 100rpx;
						color: #ccc;
					}
				}
			}
		}

		.publish-box {
			width: 100%;
			height: 200rpx;
			padding-bottom: 60rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #fff;
			padding: 20rpx 30rpx 50rpx 30rpx;
			box-sizing: border-box;

			text {
				width: 100%;
				height: 100rpx;
				border-radius: 100rpx;
				background-color: #044BAD;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
				line-height: 100rpx;
			}
		}
	}
</style>
<style scoped>
	/deep/ .input-title-placeholder {
		padding: 20rpx 10rpx;
		color: #999;
		box-sizing: border-box;
		font-size: 30rpx;
	}

	/deep/ .input-content-placeholder {
		padding: 40rpx 10rpx;
		color: #999;
		font-weight: 300;
		font-size: 26rpx;
		box-sizing: border-box;
	}
</style>